package com.snack.common.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.log4j.Logger;

/**
 * Map操作类. <br>
 * Description.
 * <p>
 * Copyright: Copyright (c) Apr 7, 2009 11:36:09 AM
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: JinLei
 * <p>
 * Version: 1.0
 * <p>
 */
public class MapUtil {
	public static final Logger logger = Logger.getLogger(MapUtil.class);

	/**
	 * MAP value
	 * 
	 * @param hm
	 * @param key
	 * @return
	 */
	public static String getMapValue(Map<String, String> hm, String key) {
		String ret = "";
		if (hm == null) {
			return "";
		}
		if (hm.containsKey(key)) {
			ret = hm.get(key) == null ? "" : hm.get(key);
		}
		return ret;
	}

	/**
	 * 将MAP中数据转化为BEAN对象
	 * 
	 * @param obj
	 * @param dataMap
	 * @return
	 */
	public static boolean mapToBean(Object obj, Map<String, String> dataMap) {
		try {
			BeanUtils.populate(obj, dataMap);
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("", ex);
			return false;
		}
		return true;
	}

	/**
	 * map 转化为 bean
	 * 
	 * @param obj
	 * @param dataMap
	 * @param isFormat
	 *            : true 需要格式化key，false 是不需要
	 * @return
	 */
	public static boolean mapToBean(Object obj, Map<String, String> dataMap,
			boolean isFormat) {
		if (isFormat) {
			// 需要format key
			dataMap = MapUtil.formatMapKeys(dataMap);
		}
		return MapUtil.mapToBean(obj, dataMap);
	}

	/**
	 * format map
	 * 
	 * @param dataMap
	 * @return
	 */
	public static Map<String, String> formatMapKeys(Map<String, String> dataMap) {
		Map<String, String> retMap = new HashMap<String, String>();
		Iterator<String> iter = dataMap.keySet().iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			String value = dataMap.get(key);
			retMap.put(MapUtil.formatKey(key, "_"), value);
		}
		return retMap;
	}

	/**
	 * format key字符串
	 * 
	 * @param str
	 *            user_name_id
	 * @param sep
	 *            _
	 * @return userNameId
	 */
	public static String formatKey(String str, String sep) {
		String ret = WordUtils.capitalize(str.toLowerCase(), sep.toCharArray());
		ret = WordUtils.uncapitalize(ret);
		return StringUtils.replace(ret, sep, "");
	}
}